package com.healthbox.appointmentservice.service.impl;

import com.healthbox.appointmentservice.DVO.AppointmentInfoDVO;
import com.healthbox.appointmentservice.common.InfoMessage;
import com.healthbox.appointmentservice.entity.AppointmentInfo;
import com.healthbox.appointmentservice.entity.AppointmentLimit;
import com.healthbox.appointmentservice.mapper.AppointmentInfoMapper;
import com.healthbox.appointmentservice.mapper.AppointmentLimitMapper;
import com.healthbox.appointmentservice.service.AppointmentInfoModifyService;
import com.healthbox.appointmentservice.service.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author pengpeng
 * @date 2022/5/22
 */
@Service
@Slf4j
public class AppointmentInfoModifyImpl implements AppointmentInfoModifyService {
    @Autowired
    private AppointmentLimitMapper limitRepo;
    @Autowired
    private AppointmentInfoMapper infoRepo;
    @Autowired
    private MessageSender messageSender;

    @Override
    public AppointmentInfoDVO addAppointment(String userPhone, Long aLid) {
        AppointmentLimit limit = limitRepo.findOneById(aLid);
        if (limit==null) return null;
        int currentNumber = limitRepo.numberOfAppointment(aLid);
        if (currentNumber >= limit.getMaxNumber()){
            log.error("预定一个已经满了的时间段");
            return null;
        }
        if (currentNumber==limit.getMaxNumber()) return null;
        AppointmentInfo info = AppointmentInfo.builder()
                .userPhone(userPhone)
                .appointmentLimit(limit)
                .build();
        infoRepo.save(info);
        if (info.getAIId()==null) return null;

        AppointmentInfoDVO appointmentInfoDVO = AppointmentInfoDVO.fromEntity(info);
        messageSender.sendMessage(InfoMessage.fromAppointmentDVO(appointmentInfoDVO));
        return appointmentInfoDVO;
    }
}
